package com.ruoyi.erp.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.domain.Department;
import com.ruoyi.erp.domain.Fitemss00;
import com.ruoyi.erp.domain.HrHiPerson;
import com.ruoyi.erp.domain.Person;
import com.ruoyi.erp.domain.Vendor;
import com.ruoyi.erp.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.erp.controller.LedyBudgetController.initAux;
import static com.ruoyi.erp.controller.LedyBudgetController.insertUser;
import static com.ruoyi.erp.controller.LedyFeeCheckinController.initAccvouch;

/**
 * 预算凭证分摊Controller
 *
 * @author ztj
 * @date 2025-11-16
 */
@RestController
@RequestMapping("/erp/budshare")
public class LedyBudgetShareController extends BaseController {
    @Autowired
    private ILedyBudgetShareService ledyBudgetShareService;
    @Autowired
    private IGlAccvouchService glAccvouchService;
    @Autowired
    private ILedyBacFeeConfigService configService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IGlCashtableService cashtableService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IHrHiPersonService hrHiPersonService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IFitemss00Service fitemss00Service;
    @Autowired
    private IFitemss97classService fitemss97classService;
    @Autowired
    private IVendorService vendorService;

    @Log(title = "凭证生成", businessType = BusinessType.IMPORT)
    @GetMapping("/sync/{ids}/{type}")
    public AjaxResult faSync(@PathVariable Long[] ids, @PathVariable String type, LedyBudget ledyOuterFeeCollect) {
        List<LedyBudgetShare> checkins = ledyBudgetShareService.selectLedyBudgetShareByIds(ids);
        GlAccvouch accvouch = new GlAccvouch();
        GlAccvouch accvouchQuery = new GlAccvouch();
        List<LedyBacFeeConfig> confList = initAccvouch(ledyOuterFeeCollect.getDbillDate(), "budget", glAccvouchService, configService, type, accvouch, accvouchQuery);
        final int[] i = {0};
        StringBuilder errTip = new StringBuilder();
        checkins.forEach(item -> {
            insertUser(i, glAccvouchService, type, accvouch, accvouchQuery);
            confList.forEach(conf -> {
                if (!conf.getItemId().equals(item.getCitemId()) || conf.getIshare() != 1) {
//                    errTip.append(item.getVouchId() + "不匹配预算类型:" + item.getcVouType() + "\n");
                    return;
                }
                errTip.append(item.getVouchId());
                i[0]++;
                LedyBudget ledyBudget = new LedyBudget();
                BeanUtil.copyProperties(item, ledyBudget);
                initAux(conf, confList, ledyBudget, accvouch, departmentService, personService, fitemss97classService, vendorService, fitemss00Service, hrHiPersonService);
                accvouch.setInid(Long.parseLong(i[0] + ""));
                accvouch.setCcode(conf.getCcode());
                accvouch.setMd("0");
                accvouch.setMc("0");

                if (conf.getRecordCate().equals("借")) {
                    accvouch.setMd(item.getMd().toString());
                } else {
                    accvouch.setMc(item.getMd().toString());
                }

                if (new BigDecimal(accvouch.getMc()).compareTo(new BigDecimal(0)) == 0 && new BigDecimal(accvouch.getMd()).compareTo(new BigDecimal(0)) == 0) {
                    i[0]--;
                    return;
                }
                accvouch.setCdigest("预算支出分摊：" + item.getVouchId() + item.getcVouType() + item.getCsupName());
                accvouch.setCcodeEqual(confList.stream().map(s -> {
                    if (!s.getCcode().equals(conf.getCcode()) && !s.getRecordCate().equals(conf.getRecordCate())) {
                        if (item.getMd().compareTo(new BigDecimal(0)) <= 0) {
                            return null;
                        }
                        return s.getCcode();
                    } else return null;
                }).distinct().collect(Collectors.joining(",")).replaceAll("null,", "").replace(",null", ""));
                accvouch.setCcodeexchEqual(accvouch.getCcodeEqual());
                glAccvouchService.insertGlAccvouch(accvouch);
                if (StringUtil.isNotEmpty(conf.getCashDesc())) {
                    GlCashtable cashtable = new GlCashtable();
                    BeanUtil.copyProperties(accvouch, cashtable);
                    cashtable.setcCashItem(conf.getCashDesc());
                    cashtableService.insertGlCashtable(cashtable);
                }
                LedyBudgetShare feeCollect = new LedyBudgetShare();
                feeCollect.setId(item.getId());
                feeCollect.setInoId(accvouch.getInoId().toString());
                feeCollect.setIflagRe(1);
                feeCollect.setDbillDate(accvouch.getDbillDate());
                ledyBudgetShareService.updateLedyBudgetShare(feeCollect);
            });


        });
        if (errTip.toString().isEmpty()) {
            return error(errTip + "科目规则不匹配！");
        }
        return toAjax(1);
    }

    /**
     * 查询预算凭证分摊列表
     */
    @PreAuthorize("@ss.hasPermi('erp:budshare:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedyBudgetShare ledyBudgetShare) {
        startPage();
        List<LedyBudgetShare> list = ledyBudgetShareService.selectLedyBudgetShareList(ledyBudgetShare);
        return getDataTable(list);
    }

    /**
     * 导出预算凭证分摊列表
     */
    @PreAuthorize("@ss.hasPermi('erp:budshare:export')")
    @Log(title = "预算凭证分摊", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LedyBudgetShare ledyBudgetShare) {
        List<LedyBudgetShare> list = ledyBudgetShareService.selectLedyBudgetShareList(ledyBudgetShare);
        ExcelUtil<LedyBudgetShare> util = new ExcelUtil<LedyBudgetShare>(LedyBudgetShare.class);
        util.exportExcel(response, list, "预算凭证分摊数据");
    }

    /**
     * 获取预算凭证分摊详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp:budshare:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ledyBudgetShareService.selectLedyBudgetShareById(id));
    }

    /**
     * 新增预算凭证分摊
     */
    @PreAuthorize("@ss.hasPermi('erp:budshare:add')")
    @Log(title = "预算凭证分摊", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedyBudgetShare ledyBudgetShare) {
        return toAjax(ledyBudgetShareService.insertLedyBudgetShare(ledyBudgetShare));
    }

    /**
     * 修改预算凭证分摊
     */
    @PreAuthorize("@ss.hasPermi('erp:budshare:edit')")
    @Log(title = "预算凭证分摊", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedyBudgetShare ledyBudgetShare) {
        return toAjax(ledyBudgetShareService.updateLedyBudgetShare(ledyBudgetShare));
    }
    @PreAuthorize("@ss.hasPermi('erp:budshare:edit')")
    @GetMapping("/editShare")
    public AjaxResult editShare(LedyBudgetShare ledyBudgetShare) {
        for (Long id : ledyBudgetShare.getIds()) {
            ledyBudgetShare.setId(id);
            ledyBudgetShareService.updateLedyBudgetShare(ledyBudgetShare);
        }
        return toAjax(1);
    }
    /**
     * 删除预算凭证分摊
     */
    @PreAuthorize("@ss.hasPermi('erp:budshare:remove')")
    @Log(title = "预算凭证分摊", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ledyBudgetShareService.deleteLedyBudgetShareByIds(ids));
    }
}
